<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <!-- 添加角色 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="showAddRole">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="roleList" border stripe>
                <el-table-column label="展开" type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item1,idx1) in scope.row.children" :key="item1.id"
                            :class="['bdbottom',idx1==0 ? 'bdtop' : 'bdbottom','vcenter']">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close='removeRightById(scope.row, item1.id)'>{{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>

                            <!-- 二级和三级权限 -->
                            <el-col :span="19">
                                <el-row v-for="(item2,idx2) in item1.children" :key="item2.id"
                                    :class="[idx2==0 ? '' : 'bdtop', 'vcenter']">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close='removeRightById(scope.row, item2.id)'>
                                            {{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3, idx3) in item2.children" :key="item3.id"
                                            closable @close='removeRightById(scope.row, item3.id)'>
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>{{scope.row}}</pre> -->
                    </template>
                </el-table-column>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="small" @click="edit">编辑</el-button>
                        <el-button type="danger" icon="el-icon-search" size="small" @click="delUser(scope.row)">删除
                        </el-button>
                        <el-button type="warning" icon="el-icon-setting" size="small"
                            @click="showSetRihgtDialog(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%" @close="addRoleClosed">
            <el-form :model="addRole" :rules="addRolRules" ref="addRolRulesRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRole.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRole.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="onAddRole">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">

            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defKeys" ref="treeRef"></el-tree>

            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                roleList: [],
                rightsList: [],
                treeProps: {
                    children: 'children',
                    label: 'authName'
                },
                roleId: 0,
                //默认选中
                defKeys: [],
                addRoleVisible: false,
                setRightDialogVisible: false,
                setRoleDialogVisible: false,
                addRole: {
                    roleName: '',
                    roleDesc: ''
                },
                addRolRules: {
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                        { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                    ]
                }
            }
        },

        created() {
            this.getRoleList()
        },

        methods: {
            async getRoleList() {
                var { data: res } = await this.$http.get('roles')
                if (res.meta.status !== 200) return this.$message.error('获取角色失败')
                this.roleList = res.data
                console.log(res);
            },
            showAddRole() {
                this.addRoleVisible = true
            },
            async onAddRole() {
                var { data: res } = await this.$http.post('roles', this.addRole)
                if (res.meta.status !== 201) return this.$message.error('添加角色失败');
                this.$message.success('角色添加成功')
                this.getRoleList()
                this.addRoleVisible = false
            },
            addRoleClosed() {
                this.$refs.addRolRulesRef.resetFields()
            },
            async delUser(user) {
                var confirm = await this.$confirm('删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                if (confirm !== 'confirm') return;
                var { data: res } = await this.$http.delete(`roles/${user.id}`)
                this.$message({ message: res.meta.msg, type: res.meta.status == 200 ? 'success' : 'warning' })
                this.getRoleList()
            },
            edit() {
                this.$message('来编辑了老弟')
            },
            async removeRightById(info, rightId) {
                //弹框删除
                var confirm = await this.$confirm('删除该权限, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                if (confirm !== 'confirm') return;
                var { data: res } = await this.$http.delete(`roles/${info.id}/rights/${rightId}`)
                this.$message({ message: res.meta.msg, type: res.meta.status == 200 ? 'success' : 'warning' })
                //根据返回数据重新渲染
                info.children = res.data
            },
            async showSetRihgtDialog(role) {
                var { data: res } = await this.$http.get('rights/tree')
                if (res.meta.status !== 200) return this.$message.error('获取权限失败')
                this.roleId = role.id
                this.rightsList = res.data
                this.getLeafKeys(role, this.defKeys)
                this.setRightDialogVisible = true
            },
            //递归获取三级ID
            getLeafKeys(node, arr) {
                if (!node.children) { //三级
                    return arr.push(node.id)
                }
                node.children.forEach(item => this.getLeafKeys(item, arr));
            },
            setRightDialogClosed() { //关闭权限框，清除数组
                this.defKeys = []
            },
            async allotRights() { //分配权限
                const keys = [
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys()
                ]

                const idStr = keys.join(',')
                var { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
                if (res.meta.status !== 200) return this.$message.error('分配权限失败')
                this.$message.success('分配权限成功')
                this.getRoleList()
                this.setRightDialogVisible = false
            }
        }
    }
</script>


<style lang="less" scoped>
    .el-tag {
        margin: 7px;
        margin-left: 15px;
    }

    .bdtop {
        border-top: 1px solid #eee;
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>